package com.jrtc.backend.controller.base;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.utils.StringUtils;
import com.jrtc.base.config.LoginException;
import com.jrtc.base.config.ParamException;
import com.jrtc.base.config.constants.Constants;
import com.jrtc.base.entity.dto.SysUserDTO;
import com.jrtc.base.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Component
public class BaseController {
    @Autowired
    private RedisUtil redis;

    /**
     * 获取当前登录的管理员
     */
    public SysUserDTO getLoginAdmin(HttpServletRequest request) {
        try {
            String token = request.getHeader("token");
            Collection<String> keys = redis.keys(Constants.DOCTOR_LOGIN_TOKEN_KEY.getValue() + "*" + token);//根据唯一的token查询出唯一key
            if (keys == null || keys.size() < 1)
                throw new LoginException("登录已过期，请重新登录");
            String key = "";
            for (String item : keys)
                key = item;
            String sysUserJson = redis.get(key).toString();
            return JSON.parseObject(sysUserJson, SysUserDTO.class);
        } catch (Exception e) {
            throw new LoginException("登录已过期，请重新登录");
        }
    }

    //验证参数
    public void verification(Object... obj) throws ParamException {
        if (obj == null || obj.length < 1) {
            throw new ParamException("参数异常");
        }
        for (Object o : obj) {
            if (o == null) {
                throw new ParamException("参数异常");
            }
            if (o instanceof List) {
                List list = (List) o;
                if (list.isEmpty()) {
                    throw new ParamException("参数异常");
                }
            } else if (o instanceof String) {
                if (StringUtils.isEmpty((String) o)) {
                    throw new ParamException("参数异常");
                }
            } else if(o instanceof Map){
                Map map = (Map)o;
                if(map.keySet().isEmpty()){
                    throw new ParamException("参数异常");
                }
            }


            }

        }
    }

